﻿namespace HuwmanCode.Net

open System
open System.IO
open System.Text
open System.Threading
open System.Net
open System.Net.Sockets
open System.Diagnostics
open System.Collections.Generic
open Microsoft.FSharp.Control.CommonExtensions

type internal FtpConnection(connection:TcpClient) =
    do FtpConnection.Send(connection.GetStream(), Response.ServiceReadyForNewUser, "FTP Server Ready")
       Async.Start(FtpConnection.Receive(connection.GetStream()))

    static member private Send(stream, response) =
        FtpConnection.Send(stream, response, String.Empty)

    static member private Send(stream, response, message) =
        if stream.CanWrite then 
            sprintf "%d %s%s" (int response) message Environment.NewLine |> stream.WriteAscii
        else failwith "Cannot send, stream is not in a writable state!"

    static member private Receive(stream:NetworkStream) =
        async { let buffer = Array.create 64 0uy
                let! bytesRead = stream.AsyncRead(buffer)
                let str = System.Text.Encoding.ASCII.GetString(buffer).Substring(0, bytesRead)
                ignore buffer }
    